<template>
  <div ref="chartRef" v-loading="loadingRef" :style="{ height, width }"></div>
</template>
<script lang="ts" setup>
import { onMounted, PropType, Ref, ref } from 'vue'
import { useECharts } from '@/hooks/web/useECharts'
import { getCompareBarChartEle } from '@/api/power/electricity/electricity'
import type { EChartsOption } from 'echarts'

defineProps({
  width: {
    type: String as PropType<string>,
    default: '100%',
  },
  height: {
    type: String as PropType<string>,
    default: '100%',
  },
})

const chartRef = ref<HTMLDivElement | null>(null)
const loadingRef = ref<Boolean>(true)

const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>)
const options: EChartsOption = {
  backgroundColor: '#fff',
  tooltip: {
    trigger: 'axis',
    appendToBody: true,
    axisPointer: {
      type: 'shadow',
      label: {
        show: true,
        backgroundColor: '#333',
      },
    },
  },
  grid: {
    left: '10px',
    right: '10px',
    bottom: '10px',
    containLabel: true,
  },
  yAxis: {
    type: 'value',
    name: 'KWh',
  },
  xAxis: {
    type: 'category',
    data: [],
  },
  barMaxWidth: 20,
  series: [],
}
onMounted(() => {
  setOptions(options)
})

const setData = (xData, yData) => {
  setOptions({
    ...options,
    legend: {
      data: yData.map((item) => item.name),
      type: 'scroll',
    },
    xAxis: {
      type: 'category',
      data: xData,
    },
    series: yData.map((item) => ({
      ...item,
      type: 'bar',
    })),
  })
}

const getData = (searchInfo) => {
  loadingRef.value = true
  // 数据环比
  getCompareBarChartEle(searchInfo)
    .then((e: any) => {
      setData(e.xaxisList, e.yaxisList)
    })
    .catch((e) => {
      setData([], [])
      loadingRef.value = true
    })
    .finally(() => {
      // const mockData = {
      //   yaxisList: [
      //     {
      //       name: '峰',
      //       data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      //       stack: '1798287086382485504',
      //     },
      //     {
      //       name: '平',
      //       data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      //       stack: '1798287311482392576',
      //     },
      //     {
      //       name: '谷',
      //       data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      //       stack: '1798287734213709824',
      //     },
      //   ],
      //   xaxisList: [
      //     '00:00',
      //     '01:00',
      //     '02:00',
      //     '03:00',
      //     '04:00',
      //     '05:00',
      //     '06:00',
      //     '07:00',
      //     '08:00',
      //     '09:00',
      //     '10:00',
      //     '11:00',
      //     '12:00',
      //     '13:00',
      //     '14:00',
      //     '15:00',
      //     '16:00',
      //   ],
      // }
      // setData(mockData.xaxisList, mockData.yaxisList)
      loadingRef.value = false
    })
}
defineExpose({
  getData,
})
</script>
